package com.example.pc.system_broadcastreceiver.receiver;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;

public class PhoneBroadcastReceiver extends BroadcastReceiver {

    //注册来电状态的广播动作
    public static final String PHONE_STATE = "android.intent.action.PHONE_STATE";
    //注册拨打电话的广播动作
    public static final String NEW_OUTGOING_CALL = Intent.ACTION_NEW_OUTGOING_CALL;

    private String TAG = PhoneBroadcastReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action == null)
            return;
        if (action.equals(NEW_OUTGOING_CALL)) {//获取拨打出去的电话号码
            String phoneNumber = intent.getExtras().getString(Intent.EXTRA_PHONE_NUMBER);
            Log.i("OUtcallREceiver", "--->电话拨出了：" + phoneNumber);
        } else if (action.equals(PHONE_STATE)) {
            Log.i(TAG, "--->电话状态改变了！");
            Bundle bundle = intent.getExtras();
            //获取拨打进来的电话号码
            String phoneNumber = bundle.getString("incoming_number");
            TelephonyManager manager = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
            int intstate = manager.getCallState();
            Log.d(TAG, "onReceive: intstate :::: "+intstate);
            switch (intstate) {
                case TelephonyManager.CALL_STATE_IDLE:
                    Log.i(TAG, "--->电话挂断了！" + phoneNumber);
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    Log.i(TAG, "--->电话接听了！" + phoneNumber);
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    Log.i(TAG, "--->电话铃声响了！" + phoneNumber);
                    break;
            }
        }
    }
}
